package com.mine.common.helper;

import com.google.gson.Gson;
import com.mine.common.config.Constant;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class QiNiuHelper {
    private static Auth sAuth;

    static {
        sAuth = Auth.create(Constant.QINIU.QINIU_ACCESSKEY, Constant.QINIU.QINIU_SECRETKEY);
    }

    public static String uploadImage(String file) throws QiniuException, UnsupportedEncodingException {
        return upload(file);
    }

    public static String uploadImage(byte[] file) throws QiniuException, UnsupportedEncodingException {
        return upload(file);
    }

    public static String uploadImage(File file) throws QiniuException, UnsupportedEncodingException {
        return upload(file);
    }


    private static String upload(Object file) throws QiniuException, UnsupportedEncodingException {
        String sUpToken = sAuth.uploadToken(Constant.QINIU.QINIU_BUCKET);
        Configuration cfg = new Configuration(Zone.zone2());
        UploadManager uploadManager = new UploadManager(cfg);
        Response response = null;
        if (file instanceof String) {
            response = uploadManager.put(String.valueOf(file), null, sUpToken);
        } else if (file instanceof byte[]) {
            response = uploadManager.put((byte[]) (file), null, sUpToken);
        } else if (file instanceof File) {
            response = uploadManager.put((File) (file), null, sUpToken);
        }
        //解析上传成功的结果
        assert response != null;
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        String encodedFileName = URLEncoder.encode(putRet.key, "utf-8");
//        String finalUrl = sAuth.privateDownloadUrl(publicUrl);//私有空间 加上签名
        return String.format("%s/%s", Constant.QINIU.QINIU_BASE_URL, encodedFileName);
    }

}
